package com.ywy.shiro;

import cn.hutool.json.JSONUtil;
import com.ywy.common.rest.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.filter.authc.UserFilter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * Shiro过滤器
 *
 * @author ywy
 * @date 2021/12/29 9:31
 */
public class AuthFilter extends UserFilter {
    @Override
    protected void redirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 如果为Ajax请求则弹窗显示未登录
        String header = httpServletRequest.getHeader("X-Requested-With");
        if (header != null && "XMLHttpRequest".equals(header)) {
            boolean authenticated = SecurityUtils.getSubject().isAuthenticated();
            if (!authenticated) {
                response.setContentType("application/json;charset=UTF-8");
                response.getWriter().print(JSONUtil.toJsonStr(Result.failure("请先登录！")));
                try {
                    httpServletRequest.getRequestDispatcher("/login").forward(request, response);
                } catch (ServletException e) {
                    e.printStackTrace();
                }
            }
        } else {
            // 如果为Web请求则重定向到登录页面
            super.redirectToLogin(request, response);
        }
    }
}
